package com.library.librarybackend.config;

import com.library.librarybackend.handler.async.AsyncTaskExecute;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 平
 * @description 异步任务配置
 * @since 2025-07-01 23:17
 */
@Data
@EnableAsync
@Configuration
@ConfigurationProperties(prefix = "async")
public class AsyncConfig implements AsyncConfigurer {
    private Integer corePoolSize = 5;

    private Integer maxPoolSize = 10;

    private Integer keepAliveSeconds = 60;

    private String threadNamePrefix = "async-thread-";


    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize); // 核心线程数
        executor.setMaxPoolSize(maxPoolSize); // 最大线程数
        executor.setKeepAliveSeconds(keepAliveSeconds); // 空闲线程存活时间
        executor.setThreadNamePrefix(threadNamePrefix); // 线程名称前缀
        //CallerRunsPolicy：调用者运行策略，当任务被拒绝时，由调用线程自己执行任务。
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Bean
    public AsyncTaskExecute asyncTaskExecute() {
        return new AsyncTaskExecute();
    }


}